package org.JWCB.common.security.service;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.JWCB.common.core.constants.CacheConstants;
import org.JWCB.common.core.constants.HttpConstants;
import org.JWCB.common.core.constants.JwtConstants;
import org.JWCB.common.core.domain.entity.LoginUser;
import org.JWCB.common.core.utils.JWTUtils;
import org.JWCB.common.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 操作用户的登录token的方法
 */

@Slf4j
@Component
public class TokenService {

    @Autowired
    private RedisService redisService;
    public  String createToken(Long userId,String nickName,String secret,Integer identity) {
      return createToken(userId,nickName,secret,identity,null);
    }

    /**
     * 根据信息得到token,将信息存入redis
     * @param userId 用户标识
     * @param nickName 昵称
     * @param secret token秘钥
     * @param identity 身份
     * @param headImage 头像
     * @return token
     */
    public String createToken(Long userId,String nickName,String secret,Integer identity,String headImage) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtConstants.LOGIN_JWT_USER_ID,userId);
        String userKey = UUID.fastUUID().toString();
        claims.put(JwtConstants.LOGIN_JWT_USER_KEY,userKey);
        String token = JWTUtils.createToken(claims,secret);

        LoginUser loginUser = new LoginUser();
        loginUser.setIdentityCode(identity);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(getLoginRedisKey(userKey),loginUser,CacheConstants.LOGIN_TOKEN_EXP, TimeUnit.MINUTES);
        return token;
    }
    /**
     * 延长token过期时间
     * @param token token
     */
    public void extendToken(String token,String secret) {
        String key = getLoginKey(token,secret);
        if(key == null) {
            log.error("在延长过期时间时token解析失败!");

            return;
        }
        Long exp = redisService.getExpire(key,TimeUnit.MINUTES);
        if(exp != null && exp <= CacheConstants.EXTENDED_CRITICAL_VALUE) {
            // 进行延长过期时间
            redisService.expire(key,CacheConstants.LOGIN_TOKEN_EXP,TimeUnit.MINUTES);
        }
    }


    /**
     * 得到存在redis里面的loginKey
     * @return loginKey
     */
    public String getLoginKey(String token,String secret) {
        if(StrUtil.isEmpty(token)) {
            return "";
        }
        if(token.startsWith(HttpConstants.TOKEN_PREFIX)) {
            token = token.replaceFirst(HttpConstants.TOKEN_PREFIX,StrUtil.EMPTY);
        }
        Claims claims;
        try {
            claims = JWTUtils.parseToken(token,secret);
            if(claims == null) {
                return null;
            }
        }catch (Exception e) {
            return null;
        }
        String userKey = JWTUtils.getUserKey(claims);
        return getLoginRedisKey(userKey);
    }

    /**
     * 在token里面获取userId
     * @return userId
     */
    public Long getUserId(String token,String secret) {
        if(token.startsWith(HttpConstants.TOKEN_PREFIX)) {
            token = token.replaceFirst(HttpConstants.TOKEN_PREFIX,StrUtil.EMPTY);
        }
        Claims claims = JWTUtils.parseToken(token,secret);
        return Long.valueOf(JWTUtils.getUserId(claims));
    }



    /**
     * 通过userId得到放在redis里的信息的key
     * @return key
     */
    private String getLoginRedisKey(String key) {
        return CacheConstants.LOGIN_TOKEN_KEY +key;
    }



    /**
     * 得到已经登录用户的信息
     * @param token 身份唯一标识
     * @param secret token 密钥
     * @return 用户信息
     */
    public LoginUser getLoginUser(String token,String secret) {
        String key = getLoginKey(token,secret);
        if(key == null) {
            log.error("token解析失败!");

            return null;
        }
        return redisService.getCacheObject(key,LoginUser.class);
    }


    /**
     * 退出登录
     * @param token 唯一标识
     * @param secret token密钥
     */
    public Boolean logout(String token, String secret) {
        String key = getLoginKey(token,secret);
        if(key == null) {
            log.error("token解析失败!");
            return false;
        }
        return redisService.deleteObject(key);
    }


    /**
     * 修改用户信息,同步到redis
     */
    public void updateLoginUserInfo(String headImage,String nickName,String userKey) {
        LoginUser loginUser = redisService.getCacheObject(userKey,LoginUser.class);
        if(loginUser == null) {
            return;
        }
        loginUser.setHeadImage(headImage);
        loginUser.setNickName(nickName);
        redisService.setCacheObject(userKey,loginUser);
    }


}
